import styles from "@pages/login/styles/styles.module.less";
import Header from "@shared/header";
import Back from "@shared/back";
// 导入表单验证的相关插件
import { SubmitHandler, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import classNames from "classnames";

// 导入登录请求的相关hook
import { useLoginMutation } from "@service/auth";
import { useNavigate } from "react-router-dom";
import toast from "react-hot-toast";
import { useEffect } from 'react'

// 导入请求用户数据hook
import { useLazyRequestProfileQuery } from "@service/user";

// 导入发送验证码组件
import SendMsgCode from "@pages/login/widgets/sendMsgCode";


import { useLocation } from "react-router-dom";

// 模式验证器
const schema = z.object({
  mobile: z
    .string({
      invalid_type_error: "手机号参数类型错误",
      required_error: "请检查字段名称是否正确",
    })
    .min(1, "请输入手机号")
    .regex(/^1[3-9]\d{9}$/, "手机号格式错误"),
  code: z
    .string({
      invalid_type_error: "验证码参数类型错误",
      required_error: "请检查字段名称是否正确",
    })
    .length(6, "验证码格式错误"),
});

//定义表单数据interface
export interface LoginFormState {
  mobile: string;
  code: string;
}

export default function LoginPage() {
  const location = useLocation();


  // 创建 JavaScript 表单对象
  const { register, handleSubmit, formState: { errors, isValid }, getFieldState, getValues } = useForm<LoginFormState>({
    // 在用户输入的过程中实时触发验证
    mode: "onChange",
    // 设置表单验证器
    resolver: zodResolver(schema),
    // 设置表单默认值
    defaultValues: { mobile: "", code: "" },
  });

  // 表单提交
  const onSubmit: SubmitHandler<LoginFormState> = (formState) => {
    // 发送登录请求
    login(formState)
      // 此处若不调用 unwrap 方法, 该 Promise 总是返回 fulfilled 状态
      .unwrap()
      .then(() => {
        // 获取登录用户资料
        requestProfile(undefined);
      })
      .catch((error) => {
        if (typeof error !== "undefined" && "status" in error) {
          const response = error.data as GeekResponse<null>;
          toast.error(response.message);
        }
      });

    // 跳转到首页
    navigate(location.state?.from || "/");
  };
  // 登录请求
  // 获取用于实现登录功能的钩子函数
  const [login, { isLoading, error, isSuccess }] = useLoginMutation();
  // 获取用于实现跳转的方法
  const navigate = useNavigate();
  // 登录成功
  useEffect(() => {
    if (isSuccess) {
      navigate("/");
      toast.success("登录成功");
    }
  }, [isSuccess]);
  // 登录失败
  useEffect(() => {
    if (typeof error !== "undefined" && "status" in error) {
      const response = error.data as GeekResponse<null>;
      toast.error(response.message);
    }
  }, [error]);

  // 发送请求获取用户信息
  const [requestProfile] = useLazyRequestProfileQuery();


  return (
    <div className={styles.login_page}>
      <Header title={""} left={<Back />} />
      <h2>短信登录</h2>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className={styles.form_item}>
          <input type="text" placeholder="请输入手机号" {...register("mobile")} />
          {errors.mobile && <p className={styles.error_message}>{errors.mobile.message}</p>}
        </div>
        <div className={styles.form_item}>
          <input type="text" placeholder="请输入验证码" {...register("code")} />
          {/* 如果验证码正在发送, className={styles.active} */}
          <SendMsgCode getFieldState={getFieldState} getValues={getValues} />
          {errors.code && <p className={styles.error_message}>{errors.code.message}</p>}
        </div>

        <button
          disabled={isLoading || !isValid}
          className={classNames(styles.login_button, {
            [styles.disabled]: isLoading || !isValid,
          })}
        >
          {isLoading ? "正在登录..." : "登录"}
        </button>
      </form>
    </div>

  );
}